//
//  OAuthViewController.swift
//  MyMicroBlog
//
//  Created by H on 15/8/2.
//  Copyright © 2015年 H. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    //栏架在控件
    private lazy var webView = UIWebView()

    override func viewDidLoad() {
        SVProgressHUD.dismiss()
        super.viewDidLoad()
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        // Do any additional setup after loading the view.
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedNetworkTools.oauthURL))
    }
    func close(){
        SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    
    }
   //加载指示器
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
  
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    
    }
    
    //加载授权页面得到code

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        // 判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedNetworkTools.redirectUrl) {
            return true
        }
        

        if let query = request.URL?.query where query.hasPrefix("code=") {
      
            // 从 query 中截取授权码得到code
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
        
            // TODO: 换取 TOKEN
            loadAccessToken(code)

        } else {
            close()
        }
        
        return false
   }
    
    //获取token的方法
    private func loadAccessToken(code:String) {
    
    NetworkTools.sharedNetworkTools.loadAccessToken(code) { (result, error) -> () in
        if error != nil || result == nil {
        
     self.netError()
            return
        }
        //将Token装换成模型
       UserAccount(dict: result!).loadUserInfo({ (error) -> () in
        if error != nil {
           self.netError()
        return
        }

       NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewControllerSwitchNotification, object: false)
        self.close()
        
       })
    
        }
    }
    /// 网络出错处理
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        
        // 延时一段时间再关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) {
            self.close()
        }
    }

}